import { createRouter, createWebHistory } from 'vue-router'

import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', component: () => import('@/views/Login/index.vue'), meta: { title: '登录' } },
    {
      path: '/',
      component: () => import('@/views/Layout/index.vue'),
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: () => import('@/views/Home/index.vue'),
          meta: { title: '首页' }
        },
        {
          path: '/article',
          component: () => import('@/views/Article/index.vue'),
          meta: { title: '文章百科' }
        },
        {
          path: '/notify',
          component: () => import('@/views/Notify/index.vue'),
          meta: { title: '消息中心' }
        },
        {
          path: '/user',
          component: () => import('@/views/User/index.vue'),
          meta: { title: '个人中心' }
        },
        {
          path: '/consult/fast',
          component: () => import('@/views/Consult/ConsultFast.vue'),
          meta: { title: '极速问诊' }
        },
        {
          path: '/consult/dep',
          component: () => import('@/views/Consult/ConsultDep.vue'),
          meta: { title: '选择科室' }
        }
      ]
    },
    {
      path: '/user/patient',
      component: () => import('@/views/User/PatientPage.vue'),
      meta: { title: '家庭档案' }
    },
    {
      path: '/consult/illness',
      component: () => import('@/views/Consult/ConsultIllness.vue'),
      meta: { title: '病情描述' }
    },
    {
      path: '/consult/pay',
      component: () => import('@/views/Consult/ConsultPay.vue'),
      meta: { title: '问诊支付' }
    }
  ]
})

router.beforeEach((to) => {
  const whiteList = ['/login', '/register']
  const store = useUserStore()
  if (!whiteList.includes(to.path) && !store.userInfo?.token) {
    // router.push('/login')
    return '/login'
  }

  Nprogress.start()
})

router.afterEach((to) => {
  document.title = `优医问诊-${to.meta.title || ''}`
  Nprogress.done()
})
Nprogress.configure({
  showSpinner: false
})

export default router
